<?php

require "include/bittorrent.php";
dbconn();
secrity();
//Send some headers to keep the user's browser from caching the response.
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-Type: text/xml; charset=utf-8");

$id = 0 + $_GET['torrentid'];
if (isset($CURUSER)) {
	$res = sql_query("SELECT id FROM blue WHERE torrentid = $id AND userid = $CURUSER[id]") or sqlerr(__FILE__, __LINE__);
	if (mysql_num_rows($res) == 0) {
		sql_query("INSERT INTO blue (torrentid, userid) VALUE ('$id', '$CURUSER[id]')") or sqlerr(__FILE__, __LINE__);
		$checkfree = get_row_count("blue", "WHERE torrentid = $id");
		$check = mysql_fetch_assoc(sql_query("SELECT sp_state FROM torrents WHERE id = $id")) or sqlerr(__FILE__, __LINE__);
		if (!empty($checkfreenum) && $checkfreenum <= $checkfree) {
			if ($check['sp_state'] == 2) {
				$updateset[] = "sp_state = 2";
				$updateset[] = "endfree = '0000-00-00 00:00:00'";
				sql_query("UPDATE torrents SET " . join(",", $updateset) . " WHERE id = $id") or sqlerr(__FILE__, __LINE__);
			} elseif ($check['sp_state'] == 4) {
				$updateset[] = "sp_state = 4";
				$updateset[] = "endfree = '0000-00-00 00:00:00'";
				sql_query("UPDATE torrents SET " . join(",", $updateset) . " WHERE id = $id") or sqlerr(__FILE__, __LINE__);
			} else {
				$updateset[] = "sp_state = 2";
				$updateset[] = "endfree = '0000-00-00 00:00:00'";
				sql_query("UPDATE torrents SET " . join(",", $updateset) . " WHERE id = $id") or sqlerr(__FILE__, __LINE__);
			}
		}
	}
	echo "pushfree";
} else {
	echo "failed";
}
